package cn.pkubangbang.demo.democontact.controller;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;

import cn.pkubangbang.demo.democontact.entity.Person;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

/**
 * note TestRestTemplate is the gift from SpringBootTest, but it is only useful in RESTful api.
 * @Author: zhangzhenbang@k2data.com.cn
 * @Date: 2018-09-11 12:51
 */
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class GeneralControllerIT {

    @Autowired
    private MockMvc mockMvc;

    private final List<Person> gangOfSeven = Arrays.asList(
        new Person(1, "熊大", Instant.EPOCH, null),
        new Person(2, "熊二", Instant.EPOCH, null),
        new Person(3, "张三", Instant.EPOCH, null),
        new Person(4, "李四", Instant.EPOCH, null),
        new Person(5, "王五", Instant.EPOCH, null),
        new Person(6, "赵六", Instant.EPOCH, null),
        new Person(7, "孙七", Instant.EPOCH, null)
    );

    @Test
    public void testServerLogin() throws Exception {

        RequestBuilder request = MockMvcRequestBuilders.get("/login");

        mockMvc.perform(request)
            .andExpect(model().attribute("people", hasSize(7)))
            .andExpect(view().name("serverLogin"))
            // note 数组相等，要使用hamcrest的equalTo，不要使用Object.equals
            .andExpect(model().attribute("people", equalTo(gangOfSeven)));

    }


}